class Solution {
public:
    vector<int> asteroidCollision(vector<int>& asteroids) {
        vector<int> st;
        int len = asteroids.size();
        // st.push_back(asteroids[0]);
        int flag = -1; // -1 和 1
        for(int i = 0; i < len; i++){
            if(flag == 1 && flag * asteroids[i] < 0){
                // 相撞
                if(-1 * asteroids[i] > st.back()){
                    int add = 1;
                    while(!st.empty()){
                        if(st.back() < 0){
                            break;
                        }
                        if(st.back() < -1 * asteroids[i]){
                            st.pop_back();
                        }else if(st.back() == -1 * asteroids[i]){
                            st.pop_back();
                            add = 0;
                            break;
                        }else{
                            add = 0;
                            break;
                        }
                    }
                    if(add){
                        st.push_back(asteroids[i]);
                    }
                    flag = -1;
                    if(!st.empty() && st.back() > 0){
                        flag = 1;
                    }
                }else if(-1 * asteroids[i] == st.back()){
                    st.pop_back();
                    if(st.empty()){
                        flag = -1;
                        continue;
                    }else{
                        if(st.back() < 0) flag = -1;
                        else flag = 1;
                    }
                }else{
                    continue;
                }
            }else{
                if(asteroids[i] > 0){
                    flag = 1;
                }else{
                    flag = -1;
                }
                st.push_back(asteroids[i]);
            }  
        }
        return st;
    }
};